<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */


//Yii::import('application.controllers.admin.BackOfficeController');
//Yii::import('Cms.services.CategoryService');
class CategoryController extends BackOfficeController
{
    public function __construct($id, $module = null){
        parent::__construct($id, $module);
        //Yii::app()->layout = 'site';
    }
    
    /**
    * Default action, list categories
    */
    public function actionIndex(){
        $this->actionList();
    }

    /**
    * List categories
    * No pagination needed
    */
    public function actionList(){
        
        $module = $this->get('module','');        
        
        $rootParamName = strtoupper($this->get('param',''));
        
        $criteria = new CDbCriteria;

        if(!empty($rootParamName) && !empty($module))
        {
            eval("\$rootCategoryId = {$module}Settings::{$rootParamName}_CAT_ID;");
            $criteria->condition = "ParentId = ".$rootCategoryId;            
        }
        else if(!empty($module))
        {
            eval("\$rootCategoryId = {$module}Settings::ROOT_CATEGORY_ID;");
            $criteria->condition = "ParentId = ".$rootCategoryId;            
        }
        else
        {
            $criteria->condition = "ParentId = 0";
        }
        $criteria->order = 'ParentId, Ordering ASC';

        // Show only top-level categories, we will use AJAX for children
        $categories = Category::model()->with('CountChildren')->findAll($criteria);

        $this->render('List',array(
            'categories'    =>$categories,
            'module'        => $module,
            'paramName'     => $rootParamName,
            'title'         => ($module == '' ? 'System' : $module) . ' categories'
        ));
    }

    /**
    * Show create form
    */
    public function actionNew() {
        $this->actionEdit();
    }
    /**
    * Show edit form
    */
    public function actionEdit(){
        $id = $this->get('categoryId', 0);
        if ($id == 0)
            $category = new Category();
        else
            $category = Category::model()->findByPk($id);        
        $this->render('Edit',array('category' => $category, 'module' => $this->get('module',''), 'param' => strtoupper($this->get('param',''))));
    }

    /**
    * Save category
    */
    public function actionSave(){
        $category = $this->post('category','');
        
        //Make sure this action can be requested only by POST
        if (Yii::app()->request->isPostRequest) 
        {
            $result = FSM::run('Core.Category.update', $_POST);
            
            if (! $result->hasErrors())
            {
                if( strcasecmp($result->action, ACTION_CREATE) == 0)
                    $this->message = Yii::t('Category','CATEGORY_CREATE_SUCCESSFUL');
                else
                    $this->message = Yii::t('Category','CATEGORY_UPDATE_SUCCESSFUL');
            }
            
            $url = $this->createUrl("/Core/category/edit", array(
                                        'categoryId' => $this->post('Category[Id]'),
                                        'module' => $this->post('module',''),
                                        'param' => $this->post('param',''),
                                        ));
            $this->redirect($url);
        }
        else
            $this->redirect($this->createUrl("Cms/admin/category/list"));
    }
    
    public function actionDeleteImage()
    {
    	// Get current info of this category
		$categoryId = $this->get('categoryId', 0);
		$category = Category::model()->findByPk($categoryId);
		
		// Delete image and its cached in system
		$filePath = Yii::getPathOfAlias('webroot') .'/' . ltrim(Utility::createImageFilename($category->Image), '/');
		if (file_exists($filePath))
		{
			unlink($filePath);
			// Update Image field in db
			$category->Image = '';	
			$category->save();
		}
		$this->redirect($this->createUrl("/Cms/admin/category/edit", array('categoryId' => $categoryId)));
    }
    
    public function actionDelete()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $result = FSM::run('Core.Category.delete', $_POST);
            echo $result->toJson();
            exit;
        }
    }
    
    public function actionGetChildCategories()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $result = FSM::run('Core.Category.findByParentId', $_POST);
            echo $result->toJson();
            exit;
        }
    }
    
    public function actionReorder()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $result = FSM::run('Core.Category.reorder', $_POST);
            echo $result->toJson();
            exit;
        }
    }
}
?>